package com.price.httplib.error

import android.accounts.NetworkErrorException
import com.google.gson.JsonSyntaxException
import com.google.gson.stream.MalformedJsonException
import com.price.common.extend.context
import com.price.core.R
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 异常工具类
 */
object ExceptionUtil {

    /**
     * 处理异常，toast提示错误信息
     */
    fun catchException(e: Throwable):HttpError {
        e.printStackTrace()
        return when (e) {
            is HttpException -> {
                HttpError(e.code(),catchHttpException(e.code()))
            }
            is SocketTimeoutException -> {
                HttpError(-1, context.getString(R.string.http_time_out))
            }
            is UnknownHostException, is NetworkErrorException -> {
                HttpError(-2, context.getString(R.string.http_net_error))
            }
            is MalformedJsonException, is JsonSyntaxException -> {
                HttpError(-3, context.getString(R.string.http_json_format_error))
            }
            is InterruptedIOException -> {
                HttpError(-4, context.getString(R.string.http_i_io_error))
            }

            is ConnectException -> {
                HttpError(-5, context.getString(R.string.http_connect_error))
            }
            else -> {
                HttpError(-6, context.getString(R.string.http_he_other))
            }
        }
    }

    /**
     * 处理网络异常
     */
    fun catchHttpException(errorCode: Int):String {
        if (errorCode in 200 until 300)
            return ""// 成功code则不处理

        return context.getString(catchHttpExceptionCode(errorCode))
    }

    /**
     * 处理网络异常
     */
    private fun catchHttpExceptionCode(errorCode: Int): Int = when (errorCode) {
        in 500..600 -> R.string.http_he_500_600
        in 400 until 500 -> R.string.http_unknown_error
        else -> R.string.http_he_other
    }
}
